package org.jetnuke.servlets.listeners;

import javax.servlet.http.HttpServletRequest;

import org.apache.velocity.VelocityContext;
import org.jetnuke.common.IAdminInfo;
import org.jetnuke.common.IUserInfo;
import org.jetnuke.common.RequestListener;
import org.jetnuke.dao.DataAccessDriver;

public class UserAgentListener implements RequestListener {

	/* (non-Javadoc)
	 * @see org.jetnuke.common.RequestListener#request(javax.servlet.http.HttpServletRequest, org.apache.velocity.VelocityContext, org.jetnuke.common.IUserInfo, org.jetnuke.common.IAdminInfo, boolean, long)
	 */
	public void request(HttpServletRequest request, VelocityContext vc,
			IUserInfo iUserInfo, IAdminInfo iAdminInfo, boolean isIndex,
			long time) {
		String ua = request.getHeader("User-Agent");//
		String browser = "Other";
		String os = "Other";
		if (ua != null) {
			ua = ua.toLowerCase();
			if ((ua.indexOf("nav") >= 0 | ua.indexOf("mozilla") >= 0
					| ua.indexOf("netscape") >= 0 | ua.indexOf("gold") >= 0 | ua
					.indexOf("x11") >= 0)
					&& (ua.indexOf("msie") == -1)
					&& (ua.indexOf("Konqueror") == -1))
				browser = "Netscape";
			else if (ua.indexOf("msie") >= 0)
				browser = "MSIE";
			else if (ua.indexOf("lynx") >= 0)
				browser = "Lynx";
			else if (ua.indexOf("opera") >= 0)
				browser = "Opera";
			else if (ua.indexOf("webtv") >= 0)
				browser = "WebTV";
			else if (ua.indexOf("konqueror") >= 0)
				browser = "Konqueror";
			else if (ua.indexOf("msie") >= 0)
				browser = "MSIE";
			else if (ua.indexOf("bot") >= 0 || ua.indexOf("google") >= 0)
				browser = "Bot";

			if (ua.indexOf("win") >= 0)
				os = "Windows";
			else if (ua.indexOf("mac") >= 0)
				os = "Mac";
			else if (ua.indexOf("linux") >= 0)
				os = "Linux";
			else if (ua.indexOf("freebsd") >= 0)
				os = "FreeBSD";
			else if (ua.indexOf("sunos") >= 0)
				os = "SunOS";
			else if (ua.indexOf("irix") >= 0)
				os = "Irix";
			else if (ua.indexOf("beos") >= 0)
				os = "BeOS";
			else if (ua.indexOf("os/2") >= 0)
				os = "OS/2";
			else if (ua.indexOf("aix") >= 0)
				os = "AIX";
		}
		//System.out.println(browser);
		//System.out.println(os);

		try {
			DataAccessDriver.getInst().newBrowserCounterDAO().incCounter(browser);
			DataAccessDriver.getInst().newOsCounterDAO().incCounter(os);
			//browser_counterPeer
				//	.executeStatement("update browser_counter set counter = counter + 1 where bid='"
					//		+ browser + "'");
			//Connection conn=JForum.getConnection();
			//Statement st=conn.createStatement();
			//st.executeUpdate("update os_counter set counter = counter +1 where oid='"
							//+ os + "'");
			//st.close();
		} catch (Throwable e) {

		}

	}

}
